<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service\Store;

use App\Constants\Business;
use App\Constants\Constants;
use App\Dao\BusinessDao;
use App\Dao\BusinessIndustryDao;
use App\Dao\CouponDao;
use App\Dao\UserDao;
use App\Kernel\Util\StoreJwtInstance;
use App\Dao\UserBankDao;
use App\Service\Service;

use Hyperf\Di\Annotation\Inject;

/**
 * 商家服务
 *
 * @author 张昊(2396675557@qq.com)
 * @package App\Service\Admin
 */
class BusinessService extends Service
{

    /**
     * @Inject
     * @var BusinessDao
     */
    public $dao;

    /**
     * @Inject
     * @var UserBankDao
     */
    public $user_bank_dao;

    /**
     * @Inject
     * @var UserDao
     */
    public $user_dao;

    /**
     * @Inject
     * @var BusinessIndustryDao
     */
    public $business_industry_dao;

    /**
     * @Inject
     * @var CouponDao
     */
    public $coupon_dao;

    /**
     * 商家审核 - 多条
     * @param array $id
     * @return mixed
     */
    public function ManyApproved(array $id)
    {
        $business_result = $this->dao->Many([
            'id' =>['in', $id]
        ],['status']);

        foreach ( $business_result as $key => $value ) {
            if( $value['status'] == 1 ) {
                $this->error('BUSINESS.NOT_STATUS');
            }

            if( $value['status'] == 3 ) {
                $this->error('BUSINESS.NOT_STATUS');
            }
        }

        $result = $this->dao->updateByIds([
            'id' => ['in', $id]
        ],[
            'status' => 1
        ]);

        if( $result ) {
            $this->coupon_dao->update([
                'business_id' => ['in', $id]
            ],[
                'status' => 1
            ]);
        }

        return $result;
    }

    /**
     * 商家审核失败 - 多条
     * @param array $id
     * @param string $audit_result
     * @return mixed
     */
    public function ManyAuditFailed(array $id, string $audit_result)
    {
        $business_result = $this->dao->Many([
            'id' =>['in', $id]
        ],['status']);

        foreach ( $business_result as $key => $value ) {
            if( $value['status'] == 1 ) {
                $this->error('BUSINESS.NOT_STATUS');
            }

            if( $value['status'] == 3 ) {
                $this->error('BUSINESS.NOT_STATUS');
            }
        }

        $result = $this->dao->updateByIds([
            'id' => ['in', $id]
        ],[
            'status' => 3,
            'audit_result' => $audit_result
        ]);

        if( $result ) {
            $this->coupon_dao->update([
                'business_id' => ['in', $id]
            ],[
                'status' => 3,
                'describe' => $audit_result
            ]);
        }

        return $result;
    }

    /**
     * 商家审核
     * @param int $id
     * @return mixed
     */
    public function Approved(int $id)
    {
        $business_result = $this->dao->first([
            'id' =>$id
        ],['status']);

        if( $business_result->status == 1 ) {
            $this->error('BUSINESS.NOT_STATUS');
        }

        if( $business_result->status == 3 ) {
            $this->error('BUSINESS.NOT_STATUS');
        }

        $result = $this->dao->update($id,[
            'status' => 1
        ]);

        if( $result ) {
            $this->coupon_dao->update([
                'business_id' => $id
            ],[
                'status' => 1
            ]);
        }

        return $result;
    }

    /**
     * 商家审核拒绝
     * @param int $id
     * @param string $audit_result
     * @return mixed
     */
    public function AuditFailed(int $id, string $audit_result)
    {
        $business_result = $this->dao->first([
            'id' =>$id
        ],['status']);

        if( $business_result->status == 1 ) {
            $this->error('BUSINESS.NOT_STATUS');
        }

        if( $business_result->status == 3 ) {
            $this->error('BUSINESS.NOT_STATUS');
        }

        $result = $this->dao->update($id,[
            'status' => 3,
            'audit_result' => $audit_result,
        ]);

        if( $result ) {
            $this->coupon_dao->update([
                'business_id' => $id
            ],[
                'status' => 3,
                'describe' => $audit_result
            ]);
        }

        return $result;
    }

    /**
     * 商家未审核 - 删除
     * @param int $id
     * @return mixed
     */
    public function delete(int $id)
    {
        $business_result = $this->dao->first([
            'id' =>$id
        ],['status']);

        if( $business_result->status == 1 ) {
            $this->error('BUSINESS.NOT_STATUS');
        }

        if( $business_result->status == 2 ) {
            $this->error('BUSINESS.NOT_STATUS');
        }

        $result = $this->dao->delete($id);

        if( $result ) {
            $this->coupon_dao->delete([
                'business_id' => $id
            ]);
        }

        return $result;
    }

    /**
     * 入驻方式
     * @param int $enable_full_discount
     * @param int $enable_coupon
     * @param int $enable_voucher
     * @return mixed
     */
    public function TextCheckStyle(int $enable_full_discount, int $enable_coupon, int $enable_voucher)
    {
        $check = '';
        if($enable_full_discount == "1") {
            $check = "全店入驻";
        }

        if($enable_coupon == "1") {
            $check = "优惠券";
        }

        if($enable_voucher == "1") {
            $check = "现金抵用券";
        }

        return $check;
    }

    public function getBizReviewList(array $params)
    {
        $map = [];
        isset($params['start_time']) && !isset($params['end_time']) && !empty($params['start_time']) && $map['created_at'] = ['>=', strtotime($params['start_time'])]; // 申请开始时间
        isset($params['end_time']) &&  !isset($params['start_time'])&& !empty($params['end_time'])  && $map['created_at'] = ['<=', strtotime($params['end_time'])]; // 申请结束时间

        isset($params['end_time']) &&  isset($params['start_time'])
        && !empty($params['end_time']) && !empty($params['start_time'])
        && $map['between_field'] = ['created_at' =>[strtotime($params['start_time']), strtotime($params['end_time'])]]; // 有申请开始和结束时间

        isset($params['industry_id'])  && !empty($params['industry_id']) && $map['industry_id'] = (int)$params['industry_id']; // 行业类别

        isset($params['tel'])  && !empty($params['tel']) && $map['tel'] = ['like', "%{$params['tel']}%"]; // 联系电话
        isset($params['legal_name'])  && !empty($params['legal_name']) && $map['legal_name'] = ['like', "%{$params['legal_name']}%"]; // 法人代表姓名/姓名

        // 入驻方式
        if (isset($params['entry_way'])) {
            switch ($params['entry_way']){
                case Business::ENABLE_FULL_DISCOUNT:
                    $map['enable_full_discount'] = 1; // 全店入驻
                    break;
                case Business::ENABLE_COUPON:
                    $map['enable_coupon'] = 1; // 优惠券
                    break;
                case Business::ENABLE_VOUCHER:
                    $map['enable_voucher'] = 1; // 现金抵用券
                    break;
                default:
                    break;
            }
        }
        isset($params['status']) && $map['status'] = (int)$params['status']; // 商户状态/0=禁用/1=正常/2=待审核/3=审核未通过

        isset($params['search'])  && !empty($params['search']) && $map['name'] = ['like', "%{$params['search']}%"]; // 搜索 /  商家名称


        $select = ['id', 'name', 'logo', 'tag', 'province', 'city', 'district', 'address', 'longitude', 'latitude', 'tel', 'full_discount_rate', 'enable_full_discount', 'enable_coupon', 'enable_voucher', 'created_at', 'legal_name', 'industry_id','status', 'phone'];
        $sort = 'created_at desc';
        // 分页
        $page_size = null;
        if (isset($params['page'])) {
            $page_size = 10;
            isset($params['page_size']) && !empty($page_size) && $page_size = (int)$params['page_size'];
        }

         $business_list = $this->dao->getBusinessByMap($map,$sort, $select, $page_size)->toArray();
        if (isset($business_list['data'])) {
            $business_list['data'] = $this->checkJoinData($business_list['data']);
        } else {
            $business_list = $this->checkJoinData($business_list);
        }
        return $business_list;
    }

    /**
     * 审查数据拼接
     * @param array $business_list
     * @return array;
     */
    public function checkJoinData(array $business_list)
    {
        foreach ($business_list as $key => $value) {
            $business_list[$key]['id'] = $value['id'];
            $business_list[$key]['created_at'] = date('Y.m.d',$value['created_at']);
            $business_list[$key]['name'] = $value['name'];
            $business_list[$key]['legal_name'] = $value['legal_name'];
            $business_list[$key]['tel'] = $value['tel'];
            $business_list[$key]['address'] = $value['province'].$value['city'].$value['district'].$value['address'];
            $business_list[$key]['check'] = $this->TextCheckStyle($value['enable_full_discount'], $value['enable_coupon'], $value['enable_voucher']);
            $business_list[$key]['industry_name'] = $this->business_industry_dao->getBusinessIndustryById( $value['industry_id'] );
            $business_list[$key]['status'] = $value['status'];
        }
        return $business_list;
    }


    /**
     * 商家审核
     * @param array $map
     * @return mixed
     */
    public function BusinessReviewList(array $map)
    {
        $result = $this->dao->BusinessReviewList($map);

        if( $result ) {
            $data['list'] = [];
            foreach ($result as $key => $value) {
                $data['list'][$key]['id'] = $value['id'];
                $data['list'][$key]['created_at'] = date('Y.m.d',$value['created_at']);
                $data['list'][$key]['name'] = $value['name'];
                $data['list'][$key]['legal_name'] = $value['legal_name'];
                $data['list'][$key]['tel'] = $value['tel'];
                $data['list'][$key]['address'] = $value['province'].$value['city'].$value['district'].$value['address'];
                $data['list'][$key]['check'] = $this->TextCheckStyle($value['enable_full_discount'], $value['enable_coupon'], $value['enable_voucher']);
                $data['list'][$key]['industry_name'] = $this->business_industry_dao->getBusinessIndustryById( $value['industry_id'] );
                $data['list'][$key]['status'] = $value['status'];
            }
            $data['count'] = count($data['list']);
        }

        return $data ?? $this->error();
    }

    /**
     * 获取提现商家详情
     * @param int $user_id
     * @return mixed
     */
    public function storeOneDetails(int $user_id)
    {
        $result = $this->dao->first([
            'user_id' => $user_id
        ]);

        if( empty($result) ) {
            $this->error();
        }

        $data['name'] = $result['name'];
        $data['legal_name'] = $result['legal_name'];
        $data['logo'] = $result['logo'];
        $data['tel'] = $result['tel'];
        $data['phone'] = $result['phone'];
        $data['forenoon_hours'] = $result['forenoon_hours'];
        $data['afternoon_hours'] = $result['afternoon_hours'];
        $data['hours_describe'] = $result['hours_describe'];
        $data['address'] = $result['province'].$result['city'].$result['district'].$result['address'];

        return $data;
    }

    /**
     * 商家审核详情
     * @param int $id
     * @return mixed
     */
    public function storeDetails(int $id)
    {
        $result = $this->dao->first([
            'id' => $id
        ]);

        if(!$result) {
            $this->error("BUSINESS.NOT_EXIST");
        }

        $bank = $this->user_bank_dao->first($result['business_bank_id']);

        $parent = $this->user_dao->first($result['parent_id']);

        $data['RealAuth']['name'] = $result['business_name'];
        $data['RealAuth']['business_card_id'] = $result['business_card_id'];
        $data['RealAuth']['business_bank_id'] = $bank['bank_account'];
        $data['RealAuth']['business_bank_name'] = $bank['bank_name'];
        $data['RealAuth']['business_status'] = $result['status'];
        $data['RealAuth']['business_created_at'] = date('Y.m.d',$result['created_at']);
        $data['RealAuth']['business_parent_name'] = $parent['name'];
        $data['RealAuth']['business_parent_code'] = $parent['identity_code'];
        $data['RealAuth']['business_idcard_positive'] = $result['business_idcard_positive'];
        $data['RealAuth']['business_idcard_negative'] = $result['business_idcard_negative'];

        $data['BusinessAuth']['business_logo'] = $result['logo'] ?? '';
        $data['BusinessAuth']['business_name'] = $result['name'];
        $data['BusinessAuth']['business_legal_name'] = $result['legal_name'];
        $data['BusinessAuth']['business_description'] = $result['description'];
        $data['BusinessAuth']['business_tel'] = $result['tel'];
        $data['BusinessAuth']['business_phone'] = $result['phone'];
        $data['BusinessAuth']['business_industry_name'] = $this->business_industry_dao->getBusinessIndustryById($result['industry_id']);
        $data['BusinessAuth']['business_address'] = $result['province'].$result['city'].$result['district'].$result['address'];
        $data['BusinessAuth']['business_company_license_pic'] = $result['company_license_pic'];
        $data['BusinessAuth']['business_other_certificates'] = json_decode($result['other_certificates']);
        $data['BusinessAuth']['business_science'] = $result['science'];


        $type = 0;
        if ( $result['enable_full_discount'] == 1 ) {
            $data['BusinessAuth']['business_type'] = "全店入驻";
            $data['BusinessAuth']['type'] = 3;
            $type = 3;
        } else if ( $result['enable_coupon'] == 1 ) {
            $data['BusinessAuth']['business_type'] = "优惠券";
            $data['BusinessAuth']['type'] = 1;
            $type = 1;
        } else if ( $result['enable_voucher'] == 1 ) {
            $data['BusinessAuth']['business_type'] = "现金抵用券";
            $data['BusinessAuth']['type'] = 2;
            $type = 2;
        }

        $couponData = $this->coupon_dao->getExamineList($type, [
            'business_id'=>$id
        ]);
        $data['CouponAuth'] = [];
        if( $couponData ) {
            foreach ( $couponData as $key => $value ) {
               $data['CouponAuth'][$key]['coupon_title'] = $value['title'];
               $data['CouponAuth'][$key]['coupon_id'] = $value['id'];
               $data['CouponAuth'][$key]['coupon_status'] = $value['status'];
               $data['CouponAuth'][$key]['coupon_picture'] = $value['picture'];
               $data['CouponAuth'][$key]['coupon_price'] = $value['price'];
               $data['CouponAuth'][$key]['coupon_goods_price'] = $value['goods_price'];
               $data['CouponAuth'][$key]['coupon_reach_price'] = $value['reach_price'];
               $data['CouponAuth'][$key]['coupon_stock'] = $value['stock'];
               if( $value['type'] == "1" ||  $value['type'] == "2" ) {
                   $data['CouponAuth'][$key]['coupon_expire_time'] = date('Y.m.d',$value['expire_time']);
               } else {
                   $data['CouponAuth'][$key]['coupon_expire_time'] = "";
               }
               $data['CouponAuth'][$key]['coupon_description'] = $value['description'];
               $data['CouponAuth'][$key]['coupon_type'] = $value['type'];
               $data['CouponAuth'][$key]['coupon_instructions'] = $value['instructions'];
            }
        }

        return $data;
    }
}